package com.itheima.reggie.controller;

import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.reggie.commen.BaseContext;
import com.itheima.reggie.commen.CustomException;
import com.itheima.reggie.commen.R;
import com.itheima.reggie.domain.*;
import com.itheima.reggie.dto.OrdersDto;
import com.itheima.reggie.service.*;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/order")
public class OrderController {

    @Autowired
    private IOrderService orderService;
    @Autowired
    private IShoppingCartService shoppingCartService;

    @Autowired
    private IUserService userService;

    @Autowired
    private IAddressBookService addressBookService;

    @Autowired
    private IOrderDetailService orderDetailService;

    @PostMapping("/submit")
    @Transactional
    public R submit(@RequestBody Orders orders) {
        Long userId = BaseContext.getCurrentId();
        LambdaQueryWrapper<ShoppingCart> qw = new LambdaQueryWrapper<>();
        qw.eq(ShoppingCart::getUserId, userId);
        List<ShoppingCart> list = shoppingCartService.list(qw);
        if (list == null || list.size() == 0) {
            throw new CustomException("购物车为空，不能下单");
        }
        User user = userService.getById(userId);
        Long addressBookId = orders.getAddressBookId();
        AddressBook addressBook = addressBookService.getById(addressBookId);
        if (addressBook == null) {
            throw new CustomException("用户地址信息有误，不能下单");
        }


        long orderId = IdWorker.getId();//订单号

        BigDecimal amount = new BigDecimal(0);//总价
        // 4、保存订单明细数据：点了哪些菜品或套餐
        for (ShoppingCart shoppingCart : list) {
            OrderDetail orderDetail = new OrderDetail();
            BeanUtils.copyProperties(shoppingCart, orderDetail);
            orderDetail.setOrderId(orderId);

            // amount 金额单独设置 数量  *  单价
            BigDecimal price = shoppingCart.getAmount();
            BigDecimal number = new BigDecimal(shoppingCart.getNumber());

            orderDetail.setAmount(price.multiply(number));
            amount=amount.add(orderDetail.getAmount());
            orderDetailService.save(orderDetail);
        }

        // 5、保存订单数据，有许多数据需要单独设置
        orders.setId(orderId);//订单id
        orders.setOrderTime(LocalDateTime.now());//订单创建时间
        orders.setCheckoutTime(LocalDateTime.now());//订单结账时间
        orders.setStatus(2);//1待付款，2待派送，3已派送，4已完成，5已取消
        orders.setAmount(amount);//总金额
        orders.setUserId(userId);//用户id
        orders.setNumber(String.valueOf(orderId));//订单号
        orders.setUserName(user.getName());//用户名
        orders.setConsignee(addressBook.getConsignee());//收货人
        orders.setPhone(addressBook.getPhone());//收货人联系电话
        orders.setAddress(
                (addressBook.getProvinceName() == null ? "" : addressBook.getProvinceName())
                        + (addressBook.getCityName() == null ? "" : addressBook.getCityName())
                        + (addressBook.getDistrictName() == null ? "" : addressBook.getDistrictName())
                        + (addressBook.getDetail() == null ? "" : addressBook.getDetail()));//省+市+区域+详细地址

        orderService.save(orders);
        LambdaQueryWrapper<ShoppingCart> qw1 = new LambdaQueryWrapper<>();
        qw1.eq(ShoppingCart::getUserId, userId);
        shoppingCartService.remove(qw1);
        return R.success(orders);
    }

    @GetMapping("/userPage")
    public R page(Integer page, Integer pageSize) {
        IPage<Orders> ordersPage = new Page<>(page, pageSize);
        LambdaQueryWrapper<Orders> qw = new LambdaQueryWrapper<>();
        qw.orderByDesc(Orders::getOrderTime);
        orderService.page(ordersPage, qw);
        List<Orders> records = ordersPage.getRecords();
        ArrayList<OrdersDto> ordersDtos = new ArrayList<>();

        for (Orders record : records) {
            OrdersDto dto = new OrdersDto();
            BeanUtils.copyProperties(record, dto);

            Long addressBookId = record.getAddressBookId();
            AddressBook addressBook = addressBookService.getById(addressBookId);
            String cityName = addressBook.getCityName();
            String provinceName = addressBook.getProvinceName();
            String districtName = addressBook.getDistrictName();
            String detail = addressBook.getDetail();
            String consignee = addressBook.getConsignee();
            String addressName = provinceName + cityName + districtName+detail;

            Long userId = record.getUserId();
            User user = userService.getById(userId);
            String userName = user.getName();
            String phone = user.getPhone();

   /*         Long id = user.getId();
            LambdaQueryWrapper<Orders> qw1 = new LambdaQueryWrapper<>();
            qw1.eq(Orders::getUserId, userId);
            Orders orders = orderService.getOne(qw1);
            String consignee = orders.getConsignee();
            Long id1 = orders.getId();*/

            LambdaQueryWrapper<OrderDetail> qw2 = new LambdaQueryWrapper<>();
            qw2.eq(OrderDetail::getOrderId, record.getId());
            List<OrderDetail> list = orderDetailService.list(qw2);



            dto.setOrderDetails(list);
            dto.setUserName(userName);
            dto.setPhone(phone);
            dto.setAddress(addressName);
            dto.setConsignee(consignee);
            ordersDtos.add(dto);
        }
        Map map = new HashMap();
        map.put("records", ordersDtos);

        return R.success(map);

    }

}
